package com.wzy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzy.base.exception.CustomException;
import com.wzy.content.mapper.TeachplanMapper;
import com.wzy.content.mapper.TeachplanMediaMapper;
import com.wzy.content.model.dto.BindTeachplanMediaDto;
import com.wzy.content.model.dto.SaveTeachplanDto;
import com.wzy.content.model.dto.TeachplanDto;
import com.wzy.content.model.po.Teachplan;
import com.wzy.content.model.po.TeachplanMedia;
import com.wzy.content.service.TeachplanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author wzy
 * @Date 2023/12/29 15:07
 * @description: 课程计划管理业务实现
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {
    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    /**
     * 根据课程id获得课程大纲目录树
     * @param courseID 课程id
     * @return
     */
    @Override
    public List<TeachplanDto> getTeachPlanTree(Long courseID) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseID);
        return teachplanDtos ;
    }

    @Transactional
    @Override
    public void updateTeachPlan(SaveTeachplanDto saveTeachplanDto) {
        if(StringUtils.isEmpty(saveTeachplanDto.getPname())){
            throw new CustomException("章节名称不能为空");
        }
        //课程计划id
        Long teachPlanId = saveTeachplanDto.getId();
        //新增章节没有id，修改章节有id
        if(teachPlanId==null){
            //新增章节信息
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            int orderByCount = getTeachPlanCount(teachplan.getCourseId(), teachplan.getParentid());
            teachplan.setOrderby(orderByCount+1);
            teachplan.setCreateDate(LocalDateTime.now());
            teachplanMapper.insert(teachplan);
        }else{
            //修改课程大纲信息
            Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
            if(teachplan==null){
                throw new CustomException("课程大纲信息为空，修改失败");
            }
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplan.setChangeDate(LocalDateTime.now());
            teachplanMapper.updateById(teachplan);
        }

    }

    /**
     * 删除课程计划
     * @param teachPlanId
     */
    @Transactional
    @Override
    public void deleteTeachPlaById(Long teachPlanId) {
        if(teachPlanId==null){
            throw new CustomException("课程计划id为空");
        }
        //根据课程计划id查询课程计划信息
        Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
        if(teachplan==null){
            throw new CustomException("课程计划为空");
        }
        //属于第一级别的章节
        if(teachplan.getGrade()==1){
            //需要判断下属还有没有第二级别的章节 有则不能删除
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            //select count(*) from teachplan where parentid = teachPlanId
            queryWrapper.eq(Teachplan::getParentid,teachPlanId);
            Integer count = teachplanMapper.selectCount(queryWrapper);
            if(count>0){
                throw new CustomException("包含子章节，不能删除！");
            }
            //否则则删除
            teachplanMapper.deleteById(teachPlanId);

        }else{
            //属于第二章节 要将对应关联的视频信息也删除
            teachplanMapper.deleteById(teachPlanId);
            //删除对应的视频信息
            LambdaQueryWrapper<TeachplanMedia> teachplanMediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teachplanMediaLambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId);
            teachplanMediaMapper.delete(teachplanMediaLambdaQueryWrapper);
        }
    }

    /**
     * 移动课程计划顺序
     * @param moveType 移动类型：movedown 下移和moveup 上移
     * @param teachPlanId 课程计划id
     */
    @Override
    public void moveTeachPlanById(String moveType, Long teachPlanId) {
        if(teachPlanId==null){
            throw new CustomException("课程计划id为空");
        }
        Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
        Integer orderby = teachplan.getOrderby();//当前计划的排序
        Integer grade = teachplan.getGrade();
        
        //下移 找到序号orderBy大于当前的orderBy的第一个
        //上移 找到序号orderBy小于当前的orderB的第一个
        if(grade==1){//当属于第一级别的章节
            //select * from teachplan where courseId = ? and grade = 1 and orderBy > orderBy ORDER BY orderby asc LIMIT 1 下移升序找第一个
            //select * from teachplan where courseId = ? and grade = 1 and orderBy < orderBy ORDER BY orderby desc LIMIT 1 上移降序找第一个
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId())
                    .eq(Teachplan::getGrade,grade)
                    .gt(moveType.equals("movedown"),Teachplan::getOrderby,orderby)
                    .lt(moveType.equals("moveup"),Teachplan::getOrderby,orderby)
                    .orderByAsc(moveType.equals("movedown"),Teachplan::getOrderby)//升序排列找第一个
                    .orderByDesc(moveType.equals("moveup"),Teachplan::getOrderby)//降序排列找第一个
                    .last(" limit 1 ");
            exchangeTeachPlanOrderBy( teachplan, queryWrapper);

        }else{
            //子章节下移
            //select * from teachplan where parentId = ? and orderBy > orderBy ORDER BY orderby asc LIMIT 1 下移升序找第一个
            //select * from teachplan where parentId = ? and orderBy < orderBy ORDER BY orderby desc LIMIT 1 上移降序找第一个
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid())
                    .gt(moveType.equals("movedown"),Teachplan::getOrderby,orderby)
                    .lt(moveType.equals("moveup"),Teachplan::getOrderby,orderby)
                    .orderByAsc(moveType.equals("movedown"),Teachplan::getOrderby)//升序排列找第一个
                    .orderByDesc(moveType.equals("moveup"),Teachplan::getOrderby)//降序排列找第一个
                    .last(" limit 1 ");
            exchangeTeachPlanOrderBy( teachplan, queryWrapper);

        }
    }

    /**
     * 课程计划绑定媒资信息
     * @param bindTeachplanMediaDto 课程计划与媒资关联信息dto
     */
    @Transactional
    @Override
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        Teachplan teachplan = teachplanMapper.selectById(bindTeachplanMediaDto.getTeachplanId());
        if(teachplan==null){
            throw new CustomException("课程计划不存在");
        }
        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,bindTeachplanMediaDto.getTeachplanId()));
        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMediaMapper.insert(teachplanMedia);
    }

    /**
     * 课程计划与视频解绑
     * @param teachPlanId 课程章节id
     * @param mediaId 媒资id
     */
    @Override
    public void mediaUnAssociation(Long teachPlanId, String mediaId) {
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId);
        queryWrapper.eq(TeachplanMedia::getMediaId,mediaId);
        teachplanMediaMapper.delete(queryWrapper);
    }

    @Override
    public List<TeachplanMedia> getTeachPlanByMediaId(String mediaId) {
        LambdaQueryWrapper<TeachplanMedia> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TeachplanMedia::getMediaId,mediaId);
        List<TeachplanMedia> teachplanMedia = teachplanMediaMapper.selectList(lambdaQueryWrapper);
        return teachplanMedia;
    }

    /**
     * 交换顺序
     * @param teachplan 要移动的课程计划
     * @param queryWrapper 查询参数
     */
    private void exchangeTeachPlanOrderBy( Teachplan teachplan,LambdaQueryWrapper<Teachplan> queryWrapper) {
        Integer orderby = teachplan.getOrderby();
        Teachplan teachPlanNext = teachplanMapper.selectOne(queryWrapper);
        if(teachPlanNext ==null){
            throw new CustomException("无法移动！");
        }
        teachplan.setOrderby(teachPlanNext.getOrderby());
        teachPlanNext.setOrderby(orderby);
        teachplanMapper.updateById(teachplan);
        teachplanMapper.updateById(teachPlanNext);
    }

    /**
     * 查询课程章节的数量，获取最新的排序号
     * @param courseId 课程id
     * @param parentId 课程计划父级id
     * @return int 最新排序号
     */
    private int getTeachPlanCount(Long courseId,Long parentId ){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }


}
